package com.lxch.gdwxp.wxpay.utils;

import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.ConnectException;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

/**
 *
 * 给微信api接口发送http请求  微信接口返回的数据格式是流，接受的请求参数格式也是流
 * 这个类会把返回的数据转换成字符串的形式
 */
public class HttpRequestUtil {

    private final static Logger log = LoggerFactory.getLogger(HttpRequestUtil.class);

    /**
     * @param requestUrl    请求URL
     * @param requestMethod 请求方式
     * @param outputStr     请求参数的流
     * @return 返回请求返回的流的JSONObject对象
     */
    public static JSONObject httpsRequestToJsonObject(String requestUrl, String requestMethod, String outputStr) {
        JSONObject jsonObject = null;
        try {
            //发请求得到 字符串类型的返回值
            StringBuffer buffer = httpsRequest(requestUrl, requestMethod, outputStr);
            System.out.println(buffer.toString() + "<<=========MyPayUtil的httpRequestToJsonObject方法35行请求返回的返回参数字符串============");
            jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (ConnectException ce) {
            log.error("===================调用微信API连接超时：" + ce.getMessage());
        } catch (Exception e) {
            log.error("=====================调用微信APIhttps请求异常：" + e.getMessage());
        }
        return jsonObject;
    }

    /**
     *
     * 发送http请求微信api接口 返回StringBuffer对象
     * @param requestUrl    请求URL
     * @param requestMethod 请求方式
     * @param output        请求参数的流对象
     * @return  微信api返回的StringBuffer类型参数
     *
     * @throws MalformedURLException
     * @throws IOException
     * @throws ProtocolException
     * @throws UnsupportedEncodingException
     */
    private static StringBuffer httpsRequest(String requestUrl, String requestMethod, String output)
            throws IOException {
        //java.net包的URL对象，java.net.ssl的HttpsURLConnection对象
        URL url = new URL(requestUrl);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setRequestMethod(requestMethod);
        //设置  请求头参数  服务器会接收到参数
        connection.setRequestProperty("Content-Type", "application/Json; charset=UTF-8");
        //把请求参数写到请求流中
        if (null != output) {
            //从连接中获取输出流对象 把请求参数写进去
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(output.getBytes("utf-8"));
            outputStream.close();
        }
        // 从连接中获取输入流对象，读取返回内容到inputStreamReader的缓冲字符流包装类bufferedReader中
        InputStream inputStream = connection.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        //创建一个接受一次读取一行数据的字符串
        String str = null;
        //创建存放返回结果的字符串缓冲对象 buffer
        StringBuffer buffer = new StringBuffer();
        while ((str = bufferedReader.readLine()) != null) {
            buffer.append(str);
        }
        bufferedReader.close();
        inputStreamReader.close();
        inputStream.close();
        inputStream = null;
        connection.disconnect();
        return buffer;
    }
}
